package com.codesuc.aichat.user.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codesuc.aichat.common.Result;
import com.codesuc.aichat.enums.CodeSucErrorEnum;
import com.codesuc.aichat.user.entity.User;
import com.codesuc.aichat.user.mapper.UserMapper;
import com.codesuc.aichat.user.service.UserService;
import cn.dev33.satoken.stp.StpUtil;
import com.codesuc.aichat.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
* @Author: ZhangGongMing
* @CreateTime: 2025/09/23 13:04
* @Description: User业务实现类
* @Version: 1.0
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Result<?> register(User user) {
        // 验证密码和确认密码是否一致
        if (user.getPassword() == null || user.getConfirmPassword() == null) {
            return Result.error("密码和确认密码不能为空");
        }
        if (!user.getPassword().equals(user.getConfirmPassword())) {
            return Result.error("两次输入的密码不一致");
        }

        // 检查用户名是否已存在
        LambdaQueryWrapper<User> usernameQuery = new LambdaQueryWrapper<>();
        usernameQuery.eq(User::getUsername, user.getUsername());
        if (baseMapper.exists(usernameQuery)) {
            return Result.buildResult(CodeSucErrorEnum.USERNAME_EXIST);
        }

        // 检查邮箱是否已存在
        if (user.getEmail() != null && !user.getEmail().trim().isEmpty()) {
            LambdaQueryWrapper<User> emailQuery = new LambdaQueryWrapper<>();
            emailQuery.eq(User::getEmail, user.getEmail());
            if (baseMapper.exists(emailQuery)) {
                return Result.error("该邮箱已被注册");
            }
        }

        // 清空确认密码字段（不保存到数据库）
        user.setConfirmPassword(null);
        
        // 保存用户（不加密密码）
        baseMapper.insert(user);
        return Result.ok("注册成功");
    }

    @Override
    public Result<Map<String, Object>> login(User user) {
        // 查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        User dbUser = baseMapper.selectOne(queryWrapper);

        // 检查用户是否存在
        if (dbUser == null) {
            return Result.error("用户不存在");
        }

        // 直接比较密码（不使用加密）
        if (!dbUser.getPassword().equals(user.getPassword())) {
            return Result.error("密码错误");
        }

        // Sa-Token登录
        StpUtil.login(dbUser.getId());

        // 设置额外信息
        StpUtil.getSession().set("username", dbUser.getUsername());

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", StpUtil.getTokenValue());
        result.put("userId", Convert.toStr(dbUser.getId()));

        return Result.ok(result);
    }
}